//
//  SPJKVC.m
//  Tunnel
//
//  Created by wbb on 2025/6/22.
//

#import "SPJKVC.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import "SPJKCell.h"
#import <SJUIKit/SJAttributeWorker.h>
#import "SJCommonProgressSlider.h"
#import "BottomPopupView.h"
@interface SPJKVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) SJVideoPlayer *player;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, copy) NSArray * dataArr;
@property (nonatomic, strong) UIButton * selectBtn;
@property (nonatomic, copy) NSString * pileNo;
@property (nonatomic, copy) NSString * direction;
@property (nonatomic, strong) BottomPopupView *popup;
@property (nonatomic, assign) NSInteger  currentIndex;
@end

@implementation SPJKVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"视频监控";
    self.pileNo = @"";
    self.direction = @"";
    [self initUI];
    [self appCameraList];
    
}
// 列表接口
- (void)appCameraList  {
    kWEAK_SELF;
    [TYNetWorkTool postRequest:@"/app/camera/list" parameters:@{
        @"direction":self.direction?:@"",
        @"pileNo":self.pileNo?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        NSArray *arr = [NSArray arrayWithArray:data[@"data"]];
        NSMutableArray *dataSourceArr = @[].mutableCopy;
        for (int i = 0; i<arr.count; i++) {
            NSMutableDictionary *itemDic = [NSMutableDictionary dictionaryWithDictionary:arr[i]];
            itemDic[@"isSelect"] = @NO;
            [dataSourceArr addObject:itemDic];
        }
        weakSelf.dataArr = [NSArray arrayWithArray:dataSourceArr];
        [weakSelf.tableView reloadData];
        if(weakSelf.dataArr.count > 0){
            weakSelf.currentIndex = 0;
            NSMutableDictionary *firstItem = weakSelf.dataArr[0]; // 直接从数据源获取可变对象
            firstItem[@"isSelect"] = @YES;
            [weakSelf getHKCode:firstItem[@"cameraId"]?:@""];
        }
        
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}
// 视频地址接口
- (void)getHKCode:(NSString *)cameraId {
    kWEAK_SELF;
    [TYNetWorkTool postRequest:@"/app/camera/getHKCode" parameters:@{
        @"cameraId":cameraId?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        NSURL *url = [NSURL URLWithString:data[@"data"][@"url"]?:@""];
        
        SJVideoPlayerURLAsset *asset = [[SJVideoPlayerURLAsset alloc] initWithURL:url];
        weakSelf.player.URLAsset = asset;
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}

- (void)onType {
    [self showPickerPopup];
}

- (void)showPickerPopup {
    if(!self.popup) {
        // 定义选项数组
        NSArray *items = @[@"南线", @"北线", @"全线",@"其他"];
        
        // 创建底部弹出选择器（默认选中第0项）
        self.popup = [BottomPopupView pickerPopupWithTitle:@"请选择"
                                                     items:items
                                             selectedIndex:0];
    }
    
    
    // 显示弹出框
    kWEAK_SELF;
    [self.popup showInViewController:[WDGlobal getCurrentViewController] animated:YES completion:^(NSInteger selectedIndex, NSString *selectedItem) {
        if (selectedIndex >= 0) {
            weakSelf.direction = [selectedItem isEqualToString: @"全线"] ? @"" : selectedItem;
            [weakSelf.selectBtn setTitle:selectedItem forState:UIControlStateNormal];
            [weakSelf appCameraList];
        } else {
        }
    }];
}
- (void)tfChange:(UITextField *)tf {
    self.pileNo = tf.text;
    NSLog(@"%@",self.pileNo);
}


// 处理 return 键点击事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder]; // 收起键盘
    // 执行搜索逻辑
    [self performSearchWithText:self.pileNo];
    
    return YES;
}

// 搜索方法
- (void)performSearchWithText:(NSString *)text {
//    if (text.length > 0) {
        NSLog(@"执行搜索: %@", text);
        // 这里添加实际的搜索代码
        [self appCameraList];
//    }
}

#pragma mark ---- UITableViewDelegate, UITableViewDataSource ----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 53;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SPJKCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [SPJKCell nibCell];
    }
    if (indexPath.row < self.dataArr.count) {
        NSDictionary *dic = self.dataArr[indexPath.row];
        [cell cellWithData:dic];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic = self.dataArr[indexPath.row];
    dic[@"isSelect"] = @YES;
    
    NSMutableDictionary *currentDic = self.dataArr[self.currentIndex];
    currentDic[@"isSelect"] = @NO;
    
    self.currentIndex = indexPath.row;
    
    [self.tableView reloadData];
    
    [self getHKCode:dic[@"cameraId"]?:@""];
}
#pragma mark ---- lazy ----
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}



- (void)initUI {
    
    _player = [SJVideoPlayer player];
    _player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
    _player.view.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 210);
    [self.view addSubview:_player.view];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.font = [UIFont systemFontOfSize:17];
    titleLab.textColor = main_text_color;
    titleLab.text = @"视频列表";
    [self.view addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.equalTo(_player.view.mas_bottom).offset(10);
    }];
    
    
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLab.mas_bottom).offset(10);
        make.left.right.equalTo(self.view);
        make.height.offset(44);
    }];
    
    UIView *layerView = [[UIView alloc] init];
    layerView.backgroundColor = hexColor(F3F3F3);
    layerView.cornerRadius = 12;
    [searchView addSubview:layerView];
    [layerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.height.offset(24);
        make.left.offset(12);
        make.right.offset(-12);
    }];
    
    UIButton *selectBtn = [UIButton buttonWithTitle:@"全线" titleColor:main_text_color font:[UIFont systemFontOfSize:14] imageName:@"select_icon"  target:self action:@selector(onType)];
    [layerView addSubview:selectBtn];
    self.selectBtn = selectBtn;
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(9);
        make.centerY.offset(0);
        
    }];
    [selectBtn layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:5];
    
    UILabel *lineLab = [[UILabel alloc] init];
    lineLab.backgroundColor = hexColor(C9C9C9);
    [layerView addSubview:lineLab];
    [lineLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn.mas_right).offset(8);
        make.width.offset(0.5);
        make.height.offset(13);
        make.centerY.offset(0);
    }];
    
    UITextField *tf = [[UITextField alloc] init];
    tf.placeholder = @"请搜索桩号";
    tf.font = [UIFont systemFontOfSize:13 weight:UIFontWeightMedium];
    [tf addTarget:self action:@selector(tfChange:) forControlEvents:UIControlEventEditingChanged];
    tf.returnKeyType = UIReturnKeySearch;
    tf.delegate = self;
    [layerView addSubview:tf];
    [tf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineLab).offset(8);
        make.centerY.offset(0);
        make.right.offset(-9);
    }];
    
    UILabel *bottomLine = [[UILabel alloc] init];
    bottomLine.backgroundColor = hexColor(ECECEC);
    [searchView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.height.offset(0.5);
    }];
    
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchView.mas_bottom);
        make.left.right.offset(0);
        make.bottom.equalTo(self.view);
    }];
}
@end
